<template>
  <v-form v-model="valid">


    <v-row>
      <v-col cols="12" lg="4" md="4" sm="12">
        <span>Territories:</span>
        <v-autocomplete
          v-model="TravelallowanceDetail.territory"
          :items="territoryList"
          :rules="rules.territory"
          chips
          dense
          item-text="Name"
          item-value="Id"
          small-chips
          solo
          @change="getprovince()"
        ></v-autocomplete>
      </v-col>
      <v-col cols="12" lg="4" md="4" sm="12">
        <span>Province:</span>
        <v-autocomplete
          v-model="TravelallowanceDetail.province"
          :disabled="isEditing"
          :items="provinceList"
          :rules="rules.province"
          chips
          dense
          item-text="Id"
          item-value="Name"
          small-chips
          solo
          @change="getaccomodationCity()"
        ></v-autocomplete>
      </v-col>
      <v-col cols="12" lg="4" md="4" sm="12">
        <span>City:</span>
        <v-autocomplete
          v-model="TravelallowanceDetail.accomodationCity"
          :disabled="isEditing"
          :items="cityList"
          :rules="rules.accomodationCity"
          chips
          dense
          item-text="Id"
          item-value="Name"
          small-chips

          solo
          @change="PutTravelAllowanceFun()"
        ></v-autocomplete>
      </v-col>

    </v-row>
    <v-row>
      <v-col cols="12" lg="4" md="4" sm="12">
        <span>Hotel Name:</span>
        <v-text-field
          v-model="TravelallowanceDetail.hotelName"
          :rules="rules.hotelName"
          dense
          solo
          @change="PutTravelAllowanceFun()"
        ></v-text-field>
      </v-col>
      <v-col cols="12" lg="4" md="4" sm="12">
        <span> Check-in Date(DD/MM/YYYY):</span>
        <v-menu
          v-model="checkInDateMenu"
          :close-on-content-click="false"
          :nudge-right="40"
          min-width="290px"
          offset-y
          transition="scale-transition"
        >
          <template v-slot:activator="{ on, attrs }">
            <v-text-field
              v-model="TravelallowanceDetail.accordingCheckInDate"
              v-bind="attrs"
              v-on="on"
              :rules="rules.CheckInDate"
              dense
              readonly
              solo
            ></v-text-field>
          </template>
          <v-date-picker
            v-model="TravelallowanceDetail.checkInDate"
            :allowed-dates="checkInDates"
            @change="PutTravelAllowanceFun()"
            @input="checkInDateMenu = false"
          ></v-date-picker>
        </v-menu>
      </v-col>
      <v-col cols="12" lg="4" md="4" sm="12">
        <span>Check-out Date(DD/MM/YYYY):</span>
        <v-menu
          v-model="checkOutDateMenu"
          :close-on-content-click="false"
          :nudge-right="40"
          min-width="290px"
          offset-y
          transition="scale-transition"
        >
          <template v-slot:activator="{ on, attrs }">
            <v-text-field
              v-model="TravelallowanceDetail.accordingCheckOutDate"
              v-bind="attrs"
              v-on="on"
              :rules="rules.CheckOutDate"
              dense
              readonly
              solo
            ></v-text-field>
          </template>
          <v-date-picker
            v-model="TravelallowanceDetail.checkOutDate"
            :allowed-dates="checkOutDates"
            @change="PutTravelAllowanceFun()"
            @input="checkOutDateMenu = false"
          ></v-date-picker>
        </v-menu>
      </v-col>
    </v-row>
    <v-row>
      <v-col cols="12" lg="4" md="4" sm="12">
        <span>No. of Nights:</span>
        <v-text-field

          v-model="TravelallowanceDetail.noOfNights"
          dense
          readonly
          solo
        ></v-text-field>
      </v-col>
      <v-col cols="12" lg="4" md="4" sm="12">
        <span> Daily Allowance(RMB):</span>
        <v-text-field

          v-model="TravelallowanceDetail.dailyAmount"
          dense
          readonly
          solo
        ></v-text-field>
      </v-col>
      <v-col cols="12" lg="4" md="4" sm="12">
        <span>Total Travel Allowance Amount(RMB):</span>
        <v-text-field
          v-model="TravelallowanceDetail.totalAmount"
          dense
          readonly
          solo
        ></v-text-field>
      </v-col>
    </v-row>
  </v-form>
</template>

<script lang="ts">
import {Component, Prop, Vue} from "vue-property-decorator";
import {
  GetCityDailyAllowanceByTerritory,
  GetTerritoryList,
  GetTerritoryListByParentId,
  PutTravelAllowance
} from "@/request/index";
import {travelallowanceDetail, travelallowanceDetailSelect} from "@/pagetypes";
import {getDaysBetween, isEmpty} from "@/utils/util"

@Component({
  components: {},
})
export default class APP extends Vue {
  // TravelallowanceDetail: travelallowanceDetail = {noOfNights: 0}
  checkInDateMenu: boolean = false
  checkOutDateMenu: boolean = false
  valid: boolean = true
  territoryList: travelallowanceDetailSelect[] = [];
  provinceList: travelallowanceDetailSelect[] = [];
  cityList: travelallowanceDetailSelect[] = [];
  isActive: boolean = true;
  isEditing: boolean = true
  @Prop({type: Object, default: {}}) travelallowance !: travelallowanceDetail;
  rules: any = {
    territory: [(val: string) => (val || '').length > 0 || 'This field is required'],
    province: [(val: string) => this.travelallowance.territory == "Mainland China" ? (val || '').length > 0 || 'This field is required' : ""],
    accomodationCity: [(val: string) => this.travelallowance.territory == "Mainland China" ? (val || '').length > 0 || 'This field is required' : (val || '').length > 0 || 'This'],
    hotelName: [(val: string) => (val || '').length > 0 || 'This field is required'],
    CheckOutDate: [(val: string) => (val || '').length > 0 || 'This field is required'],
    CheckInDate: [(val: string) => (val || '').length > 0 || 'This field is required'],

  }

  // @Watch('travelallowance')
  // ontravelallowanceChangeValue(val: travelallowanceDetail) {
  //   this.TravelallowanceDetail = val;

  // }
  get TravelallowanceDetail() {
    return this.travelallowance;
    this.travelallowance.accomodationCity
  }

  set TravelallowanceDetail(item: travelallowanceDetail) {
    this.$emit("update:travelAllowance", item)
  }

  getaccomodationCity() {
    var province: travelallowanceDetailSelect = this.provinceList.filter(x => x.Name == this.TravelallowanceDetail.province)[0]
    GetTerritoryListByParentId(province.SelectId).then((res: any) => {
      if (res.data) {
        res.data.forEach((x: any) => {
          this.cityList.push({Id: x.name, Name: x.name, SelectId: x.maintainId});
        })
      }
    })
    this.PutTravelAllowanceFun()
  }

  async getprovince() {
    if (this.travelallowance.territory == "Mainland China") {
      this.isEditing = false;
      var territory: travelallowanceDetailSelect = this.territoryList.filter(x => x.Id == this.travelallowance.territory)[0]
      await GetTerritoryListByParentId(territory.SelectId).then((res: any) => {
        if (res.data) {
          res.data.forEach((x: any) => {
            this.provinceList.push({Id: x.name, Name: x.name, SelectId: x.maintainId});
          })
        }
      })
    } else
      this.isEditing = true;
    this.PutTravelAllowanceFun()
  }


  async mounted() {
    setTimeout(async () => {
      var territoryResult = await GetTerritoryList();
      if (territoryResult.data) {
        territoryResult.data.forEach((x: any) => {
          this.territoryList.push({Id: x.name, Name: x.name + "-" + x.nameCN, SelectId: x.maintainId});
        });
        if (!isEmpty(this.TravelallowanceDetail.territory) && this.TravelallowanceDetail.territory == "Mainland China") {
          await this.getprovince()
          if (!isEmpty(this.TravelallowanceDetail.province)) {

            this.getaccomodationCity()
          }
        }
      }
    }, 500)

  }


  async PutTravelAllowanceFun() {
    this.TravelallowanceDetail.accordingCheckInDate = this.TravelallowanceDetail.checkInDate == "1901-01-01T00:00:00" ? "" : this.dayjs(this.TravelallowanceDetail.checkInDate).format("DD/MM/YYYY")
    this.TravelallowanceDetail.accordingCheckOutDate = this.TravelallowanceDetail.checkOutDate == "1901-01-01T00:00:00" ? "" : this.dayjs(this.TravelallowanceDetail.checkOutDate).format("DD/MM/YYYY")
    if (!isEmpty(this.TravelallowanceDetail.territory) && !isEmpty(this.TravelallowanceDetail.checkInDate) && !isEmpty(this.TravelallowanceDetail.checkOutDate)) {
      var days = getDaysBetween(this.TravelallowanceDetail.checkInDate, this.TravelallowanceDetail.checkOutDate);
      this.TravelallowanceDetail.noOfNights = parseInt(days);
      if (this.TravelallowanceDetail.noOfNights == 0) {
        this.TravelallowanceDetail.noOfNights = 1;
      }
      await GetCityDailyAllowanceByTerritory(this.TravelallowanceDetail.territory).then((res) => {
        if (res.data) {
          this.TravelallowanceDetail.dailyAmount = res.data.amountRMB;
          this.TravelallowanceDetail.totalAmount = this.TravelallowanceDetail.noOfNights * res.data.amountRMB;
        }
      });
    }
    PutTravelAllowance(this.TravelallowanceDetail);
  }

  getCurrentCheckInDate(): any {
    return this.TravelallowanceDetail.checkInDate;
  }

  checkOutDates = (val: any) =>
    this.getCurrentCheckInDate() == null
      ? true
      : Date.parse(val) >
      Date.parse(
        this.getCurrentCheckInDate().split("/").reverse().join("-")
      ) -
      8.64e7;
  checkInDates = (val: any) =>
    Date.parse(val) < Date.now() - 8.64e7;

}
</script>
